using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;

namespace Tool
{
    public static partial class ExtensionHelper
    {
        /// <summary>
        /// 返回时间（DateTime）
        /// </summary>
        /// <param name="str"></param>
        /// <param name="state">状态 true 表示成功 false 表示失败</param>
        /// <returns>DateTime</returns>
        public static DateTime ToDateTime(this string str, out bool state)
        {
            DateTime result = DateTime.Now;
            state = DateTime.TryParse(str, out result);
            return result;
        }

        #region ToString  把 List<T> 按照分隔符组装成 string

        /// <summary>
        /// 把 List<T> 按照分隔符组装成 string
        /// </summary>
        /// <param name="list"></param>
        /// <param name="speater"></param>
        /// <returns></returns>
        public static string ToString<T>(this List<T> list, string speater)
        {
            var sb = new StringBuilder();
            for (var i = 0; i < list.Count; i++)
            {
                sb.Append(i == list.Count - 1 ? list[i].ToString() : $"{list[i]}{speater}");
            }
            return sb.ToString();
        }

        #endregion ToString  把 List<T> 按照分隔符组装成 string

        public static string ToStringEx(this Exception exception)
        {
            StringBuilder stringBuilder = new StringBuilder();
            stringBuilder.AppendLine("====================EXCEPTION====================");
            stringBuilder.AppendLine("【Message】:" + exception.Message);
            stringBuilder.AppendLine("【Source】:" + exception.Source);
            stringBuilder.AppendLine("【TargetSite】:" + ((exception.TargetSite != null) ? exception.TargetSite.Name : "无"));
            stringBuilder.AppendLine("【StackTrace】:" + exception.StackTrace);
            stringBuilder.AppendLine("【exception】:" + exception);
            stringBuilder.AppendLine("=================================================");
            if (exception.InnerException != null)
            {
                stringBuilder.AppendLine("====================INNER EXCEPTION====================");
                stringBuilder.AppendLine("【Message】:" + exception.InnerException.Message);
                stringBuilder.AppendLine("【Source】:" + exception.InnerException.Source);
                stringBuilder.AppendLine("【TargetSite】:" + ((exception.InnerException.TargetSite != null) ? exception.InnerException.TargetSite.Name : "无"));
                stringBuilder.AppendLine("【StackTrace】:" + exception.InnerException.StackTrace);
                stringBuilder.AppendLine(("【InnerException】:" + exception.InnerException) ?? "");
                stringBuilder.AppendLine("=================================================");
            }
            return stringBuilder.ToString().Replace("/r", "").Replace("/n", "");
        }

        /// <summary>
        /// 尝试将键和值添加到字典中：如果不存在，才添加；存在，不添加也不抛导常
        /// </summary>
        public static Dictionary<TKey, TValue> TryAdd<TKey, TValue>(this Dictionary<TKey, TValue> dict, TKey key,
            TValue value)
        {
            if (dict.ContainsKey(key) == false) dict.Add(key, value);
            return dict;
        }

        /// <summary>
        /// 将键和值添加或替换到字典中：如果不存在，则添加；存在，则替换
        /// </summary>
        public static Dictionary<TKey, TValue> AddOrUpdate<TKey, TValue>(this Dictionary<TKey, TValue> dict, TKey key,
            TValue value)
        {
            if (!dict.ContainsKey(key))
            {
                dict.Add(key, value);
            }
            else
            {
                dict[key] = value;
            }

            return dict;
        }

        public static TValue GetValue<TKey, TValue>(this Dictionary<TKey, TValue> dict, TKey key)
        {
            if (dict.ContainsKey(key)) return dict[key];
            return default(TValue);
        }

        /// <summary>
        /// 数据验证返回
        /// </summary>
        /// <param name="modelState"></param>
        /// <returns></returns>
        public static object JsonResult(this Microsoft.AspNetCore.Mvc.ModelBinding.ModelStateDictionary modelState, bool isReutrnMultipleErrors = false)
        {
            var resultdata = new ResultData<string>();
            //var verifications = modelState.ToDictionary(x => x.Key, v => string.Join(",", v.Value.Errors.Select(o => o.ErrorMessage)));
            var verifications = modelState.Where(o => o.Value.Errors.Count > 0).ToDictionary(x => x.Key, v => string.Join(",", v.Value.Errors.Select(o => o.ErrorMessage)));
            if (isReutrnMultipleErrors)
            {
                resultdata.Errors = verifications;
            }
            else
            {
                resultdata.Errors = verifications.FirstOrDefault().Value;
            }

            //resultdata.Msg = string.Join(",", modelState.SelectMany(_ => _.Value.Errors.Select(e => e.ErrorMessage)).ToList());

            return resultdata;
        }
        #region 序列化、反序列化，【进行简单封装，以便更简单的使用，懒】
        /// <summary>
        /// 序列化为Json字符串（Newtonsoft.Json）
        /// </summary>
        /// <typeparam name="T">对象</typeparam>
        /// <param name="obj">序列化的对象</param>
        /// <returns></returns>
        public static string ToJson2<T>(this T obj)
        {
            //Newtonsoft.Json.JsonSerializerSettings settings = new Newtonsoft.Json.JsonSerializerSettings();
            //settings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
            //settings.MissingMemberHandling = Newtonsoft.Json.MissingMemberHandling.Ignore;
            string result = Newtonsoft.Json.JsonConvert.SerializeObject(obj, AppEx.GetDefaultJsonSerializerSettings);
            return result;
        }

        /// <summary>
        /// 反序列化为对象（Newtonsoft.Json）
        /// </summary>
        /// <typeparam name="T">对象</typeparam>
        /// <param name="jsonStr">json字符串</param>
        /// <returns></returns>
        public static T ToObj2<T>(this string jsonStr)
        {
            return Newtonsoft.Json.JsonConvert.DeserializeObject<T>(jsonStr);
        }
        /// <summary>
        /// 序列化为Json字符串（System.Text.Json）
        /// </summary>
        /// <typeparam name="T">对象</typeparam>
        /// <param name="obj">序列化的对象</param>
        /// <returns></returns>
        public static string ToJson<T>(this T obj)
        {
            string result = System.Text.Json.JsonSerializer.Serialize(obj, AppEx.GetDefaultJsonSerializerOptions);
            return result;
        }
        /// <summary>
        /// 反序列化为对象（System.Text.Json）
        /// </summary>
        /// <typeparam name="T">对象</typeparam>
        /// <param name="jsonStr">json字符串</param>
        /// <returns></returns>
        public static T ToObj<T>(this string jsonStr)
        {
            return System.Text.Json.JsonSerializer.Deserialize<T>(jsonStr);
        }
        #endregion
    }
}